package com.salim.leetcode.$2;

/**
 * Created with IntelliJ IDEA.
 * User: clevo
 * Date: 15-7-16
 * Time: 下午10:25
 * To change this template use File | Settings | File Templates.
 */
public class AddTwoNumbers {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = new ListNode(l1.val);
        ListNode start = result;
        ListNode end = new ListNode(0);
        int addflag = 0;
        while(l1 != null || l2 != null){
            if(l2 == null){
                l2 = new ListNode(0);
            }else if(l1 == null){
                l1 = new ListNode(0);
            }


            int sum = l1.val + l2.val + addflag;
            addflag = 0;
            if(sum > 9){
                addflag = 1;
                sum %= 10;
            }
            result.val = sum;
            l1 = l1.next;
            l2 = l2.next;
            result.next = new ListNode(0);
            end = result;
            result = result.next;
        }
        if(addflag == 1){
            end.next = new ListNode(1);
        }
        return start;
    }

    public static void main(String[] args){
        AddTwoNumbers a = new AddTwoNumbers();
        ListNode a1 = new ListNode(4);
        ListNode b1 = new ListNode(5);
        b1.next = new ListNode(7);
        System.out.println(a.addTwoNumbers(a1,b1));
    }
}
